
package com.netease.xone.fragment;

import protocol.XoneCallBack;
import protocol.XoneService;
import protocol.XoneServiceCode;
import protocol.meta.User;
import Utils.XoneUtil;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.netease.log.NTLog;
import com.netease.pkgRelated.XoneConsts.ACCOUNT_TYPE;
import com.netease.pkgRelated.XoneConsts.BUNDLE_KEY;
import com.netease.pkgRelated.XoneConsts.WB_LOGIN_TYPE;
import com.netease.share.ShareBind;
import com.netease.share.ShareCallback;
import com.netease.share.ShareResult;
import com.netease.share.ShareService;
import com.netease.share.ShareType;
import com.netease.share.bind.ShareWebView;
import com.netease.share.db.ManagerShareBind;
import com.netease.share.sina.ShareChannelSina;
import com.netease.xone.R;
import com.netease.xone.app.SharedKeyMgr;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.sso.SsoHandler;

import db.manager.ManagerAccount;

public class FragmentWBLogin extends FragmentBase {

    private final String TAG = "FragmentWBBind";
    private boolean mFromShare = false;// 分享之前的绑定，绑定之后跳转到发送微博界面

    private LinearLayout mWaitLay;
    private ShareWebView mWebView;
    private ShareType mShareType;
    private int mAction;
    private FrameLayout mSetNickView;
    private EditText mNickName;
    private TextView mSubmit;

    private SsoHandler mSsoHandler;
    private int mLoginTransId;
    private ShareBind mShareBind;

    private boolean mBRegister = false;
    private int mLoginType;

    public static FragmentWBLogin newInstance(int action, int type) {
        FragmentWBLogin fragment = new FragmentWBLogin();
        Bundle b = new Bundle();
        b.putInt(BUNDLE_KEY.WB_LOGIN_TYPE, action);
        b.putInt(BUNDLE_KEY.WB_BIND_TYPE, type);
        fragment.setArguments(b);
        return fragment;
    }

    public SsoHandler getSsoHandler() {
        return mSsoHandler;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        int type = 0;
        if (bundle != null && bundle.containsKey(BUNDLE_KEY.WB_LOGIN_TYPE)
                && bundle.containsKey(BUNDLE_KEY.WB_BIND_TYPE)) {
            mAction = bundle.getInt(BUNDLE_KEY.WB_LOGIN_TYPE);
            type = bundle.getInt(BUNDLE_KEY.WB_BIND_TYPE);
        }
        if (type > 0) {
            mShareType = ShareType.valueOf(type);
        } else {
            showToast(R.string.please_select_one_weibo_account_first);
            getActivity().finish();
        }
        String title = getWeiboName(getActivity(), mShareType);
        getActivity().setTitle(title);

        if (mAction == WB_LOGIN_TYPE.Login) {
            switch (mShareType) {
                case Sina:
                    mLoginType = ACCOUNT_TYPE.Sina;
                    break;
                case Qqmblog:
                    mLoginType = ACCOUNT_TYPE.Tencent;
                    break;
                case Renren:
                    mLoginType = ACCOUNT_TYPE.Renren;
                    break;
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_wb_bind, container, false);
        findViews(view);
        return view;
    }

    private void findViews(View view) {
        mWebView = (ShareWebView)view.findViewById(R.id.ShareWebView);
        mSetNickView = (FrameLayout)view.findViewById(R.id.set_nickname);
        mNickName = (EditText)view.findViewById(R.id.editNickNameInput);
        mSubmit = (TextView)view.findViewById(R.id.Submit);
        // 设置昵称
        mNickName.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    return;
                }
                int len = 0;
                for (int i = 0; i < s.length(); i++) {
                    String ss = Character.toString(s.charAt(i));
                    if (ss.matches("[\\u4E00-\\u9FA5]")) {
                        len += 2;
                    } else {
                        len++;
                    }
                    if (len > getActivity().getResources().getInteger(R.integer.nicknameMaxLen)) {
                        showToast(R.string.textNumExceedLimit);
                        String sss = s.subSequence(0, i).toString();
                        mNickName.setText(sss);
                        mNickName.setSelection(sss.length());
                        break;
                    }
                }
                // String nickname = mNickName.getText().toString().trim();
            }
        });
        mSubmit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                doRegister();
            }
        });
        if (mAction == WB_LOGIN_TYPE.Bind) {
            ShareService.getShareService().setPreferKey(
                    ManagerAccount.getInstance().getCurrentAccountName());
        } else {// WB_LOGIN_TYPE.Login
            ShareService.getShareService().setPreferKey(null);
        }
        if (mShareType != ShareType.Sina) {
            mWebView.initShareBind(mShareType, mShareCallback);
        } else {
            mWebView.setVisibility(view.GONE);
            clearCookie();
            Weibo mWeibo = Weibo.getInstance(SharedKeyMgr.SINA_CLIENT_ID,
                    SharedKeyMgr.SINA_REDIRECT_URI);
            mWeibo.setDialogOnCancelListener(new DialogInterface.OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialog) {
                    getActivity().finish();
                }
            });
            mSsoHandler = new SsoHandler(getActivity(), mWeibo);
            mSsoHandler.authorize(new AuthDialogListener());
        }
    }

    private void clearCookie() {
        CookieSyncManager.createInstance(getActivity().getApplicationContext());
        CookieManager.getInstance().removeAllCookie();
        CookieSyncManager.getInstance().sync();
    }

    class AuthDialogListener implements WeiboAuthListener {

        @Override
        public void onComplete(Bundle values) {
            String token = values.getString("access_token");
            String uid = values.getString("uid");
            // expires_in 有效期，单位：毫秒；仅当从服务器获取到expires_in时适用，表示距离超过认证时间还有多少秒
            String expiresIn = values.getString("expires_in");
            long expiresTime = System.currentTimeMillis() + Long.parseLong(expiresIn) * 1000;
            // showWatting("等待。。");
            ShareChannelSina.ssoLogin(token, null, expiresTime, uid, null, mShareCallback);

            // SinaService.getInstance().getOauthClient().setToken(token, null);
            // SinaService.getInstance().doUserShow(uid, mTransListener);
        }

        @Override
        public void onError(WeiboDialogError e) {
            showToast(e.getMessage());
            getActivity().finish();
        }

        @Override
        public void onCancel() {
            getActivity().finish();
        }

        @Override
        public void onWeiboException(WeiboException e) {
            showToast(e.getMessage());
            getActivity().finish();
        }
    }

    private String getWeiboName(Context context, ShareType type) {
        int textResId = 0;
        switch (type) {
            case Netease:
                textResId = R.string.weibo_type_netease_name_text;
                break;
            case Sina:
                textResId = R.string.weibo_type_sina_name_text;
                break;
            case Qqmblog:
                textResId = R.string.weibo_type_tencent_name_text;
                break;
            case Renren:
                textResId = R.string.weibo_type_renren_name_text;
                break;
            case Tencent:
                textResId = R.string.weibo_type_qzone_name_text;
                break;
            default:
                break;
        }

        return context.getString(textResId);
    }

    private void switchToEditNickName() {
        if (mSetNickView.getVisibility() != View.VISIBLE) {
            mSetNickView.setVisibility(View.VISIBLE);
            mSetNickView.findViewById(R.id.nick_tips).setVisibility(View.VISIBLE);
            if (mShareBind != null && mShareBind.getName() != null) {
                mNickName.setText(mShareBind.getName());
            }
            getActivity().setTitle(R.string.nicknamSet);
        }
    }

    private void doLogin(int type, String user, String pwd) {
        mBRegister = false;
        showWatting(getString(R.string.logining));
        XoneService.getInstance().addListener(mXoneCallBack);
        mLoginTransId = XoneService.getInstance().doLogin(type, user, pwd);
    }

    private void doRegister() {
        mBRegister = true;
        String nicknameStr = mNickName.getText().toString().trim();
        int msgid = -1;
        if (TextUtils.isEmpty(nicknameStr)) {
            msgid = R.string.inputNicknamePrompt;
        } else if (XoneUtil.getNicknameLen(nicknameStr) < getActivity().getResources().getInteger(
                R.integer.nicknameMinLen)) {
            msgid = R.string.nicknameLenUnreachFour;
        } else if (XoneUtil.getNicknameLen(nicknameStr) > getActivity().getResources().getInteger(
                R.integer.nicknameMaxLen)) {
            msgid = R.string.nicknameLenOverCeiling;
        } else if (XoneUtil.isNicknameContainsSpecialChar(nicknameStr)) {
            msgid = R.string.nicknameContainsSpecialChar;
        }
        if (msgid > 0) {
            showToast(msgid);
            return;
        }
        if (mShareBind != null) {
            showWatting(getString(R.string.registering));
            XoneService.getInstance().addListener(mXoneCallBack);
            mLoginTransId = XoneService.getInstance().doExternalUserReg(mShareBind.getUserID(),
                    mShareBind.getAccessToken(), mLoginType, nicknameStr, mShareBind.getProfile());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        XoneService.getInstance().removeListener(mXoneCallBack);

    }

    ShareCallback mShareCallback = new ShareCallback() {

        @Override
        public void onShareSuccess(int tid, ShareResult shareResult) {
            Log.i("onShareSuccess", "result: " + shareResult.getShareBind().getName());
            if (mShareCallback != null) {
                mShareCallback = null;
                if (mAction == WB_LOGIN_TYPE.Bind) {
                    showToast(R.string.user_setting_weibo_successfully_text);
                    XoneService.getInstance().doSyncBindingInfo(
                            ManagerAccount.getInstance().getCurrentAccountName());
                    getActivity().setResult(Activity.RESULT_OK);
                    getActivity().finish();
                } else {
                    if (shareResult != null) {
                        mShareBind = shareResult.getShareBind();
                        doLogin(ACCOUNT_TYPE.Sina, mShareBind.getUserID(),
                                mShareBind.getAccessToken());
                    }
                }
            }
        }

        @Override
        public void onShareError(int tid, ShareResult shareResult) {
            showToast("onShareError ");
        };

    };
    private XoneCallBack mXoneCallBack = new XoneCallBack() {

        @Override
        public void onLogin(int transactionId, User account) {
            if (mLoginTransId == transactionId) {
                NTLog.v(TAG, "onLogin + " + account);
                stopWaiting();
                XoneService.getInstance().removeListener(mXoneCallBack);
                if (mBRegister && mShareBind != null) {
                    ManagerShareBind.addShareBind(mShareBind.getUserID(), mShareBind);
                }
                if (mShareBind != null) {
                    XoneService.getInstance().doSyncBindingInfo(mShareBind.getUserID());
                }
                getActivity().finish();
            }
        }

        @Override
        public void onLoginError(int transactionId, int errCode, String err) {
            if (mLoginTransId == transactionId) {
                stopWaiting();
                if (XoneServiceCode.LOGINREG_ERR_XONE_USERNONE == errCode) {
                    switchToEditNickName();
                } else {
                    showToast(err);
                }
                XoneService.getInstance().removeListener(mXoneCallBack);
            }
        }
    };
}
